﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using Newtonsoft.Json.Linq;
using WebService.VO;
using System.Text;
using System.Data;
using WebService.BUS;

namespace WebService.DAO
{
    public class GooglePlaces
    {
        static string[] key = { "AIzaSyBgI2APlGovSHmm32ccbXxzpmMsr0p5aU0", "AIzaSyDEf6mVsXHR35JrxnZP11GVlBu6MSJUCDY", "AIzaSyDr3s3Q0HHj3PzwvoWiSs0Vem1-93GtYVY", "AIzaSyCjC6G_ZUjaS6u_v21EKuhevGxOh6YPfUU",
                              "AIzaSyDVHe3U7O3fYl-4zZRP_--Ss4M0DJzyTj0", "AIzaSyB6sFxEYQeYpHkH8xaJjce2J1--kPkwZRg","AIzaSyDXDw2Z_tfSH1e1YBm92dF0BFIOg3DHsXQ","AIzaSyDivyJSLxhlgl2UXRWeU2qYIP4DIUb6LtU",
                              "AIzaSyAj0EvaWmsEG03vtV1ezEsBXYBQKWnCh1I", "AIzaSyBanFI8Pu46c_CT9zDAkTK7Rb_ebwUPbBo", "AIzaSyANxf7X1Tdjq1RE_KyJj448l526ZbfaHxE", "AIzaSyAOtVENJEVPVqHU_1SkimRC07GgybD8aV4",
                              "AIzaSyAh7abVzYoj_GgfFQNXiRPHRz5_0J9y_z0", "AIzaSyCN5lXV_g-I_3JlyLMAc5i78rtbBg3sZLM", "AIzaSyBqtu5O7_a5nN-173pWm9DEga2yUutBfyM", "AIzaSyDUgpshdUsIDd__0oGLnlTUmdlorCrqI2c",
                              "AIzaSyDSeAKesbjDSvbXQHr97DLqMca-_YBPJm4", "AIzaSyChleGRVZeJEdbjwO2Gfrv8FiJjLxuOtms", "AIzaSyCCE9FNiU7AiGjh2GIOe2yTyH6RD0ly8oU", "AIzaSyA2W10syA4x0sNevzyEUDA27Qh84sg5eH4"};
        public static string[] types = { "scenic","beach", "resort", "cafe", "restaurant", "lodging", "museum", "bus_station",
                                           "gas_station","airport","train_station", "park","movie_theater", "grocery_or_supermarket", 
                                           "bank", "hospital", "post_office", "atm", "bar|night_club", "spa|beauty_salon|hair_care"};
        
        private static string NEAR_PLACE_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";


        public static DataTable parse2List(string location, string type, int id, string pagetoken)
        {
            WebClient c = new WebClient();
            DataTable dt2 = new DataTable();
            DataTable dt1 = new DataTable();
            DataTable dtAll = new DataTable();
            dtAll.AcceptChanges();
            dt2.AcceptChanges();
            dt2.Columns.Add("Name", typeof(string));
            dt2.Columns.Add("Lat", typeof(string));
            dt2.Columns.Add("Lng", typeof(string));
            dt2.Columns.Add("Vicinity", typeof(string));
            StringBuilder url = new StringBuilder() ;
            url.Append(NEAR_PLACE_URL + "location=" + location + "&radius=5000&types=" + type + "&sensor=false&language=vi&key=" + key[id] + pagetoken);
            StringBuilder page_token = new StringBuilder();
            
            Console.WriteLine(url);
            c.Encoding = Encoding.UTF8;
            var data = c.DownloadString(url.ToString());
            Console.WriteLine(data);
            JObject o = JObject.Parse(data);
            string status = o["status"].ToString();
            if (status.Equals("OK"))
            {
                JArray array = JArray.FromObject(o["results"]);
                foreach (var result in array)
                {
                    dt2.Rows.Add(result["name"].ToString(), result["geometry"]["location"]["lat"].ToString(), result["geometry"]["location"]["lng"].ToString(), result["vicinity"].ToString());
                }

                dtAll.Merge(dt2.Copy());
                if (o["next_page_token"] != null)
                {
                    page_token.Append("&pagetoken=" + o["next_page_token"].ToString().Trim());
                    dt1 = parse2List(location, type, id, page_token.ToString());
                    dtAll.Merge(dt1.Copy());
                }
            }          
            
            
           return dtAll;
        }


        public static DataTable parse2dt(string location, string type, int id, string lang, int radius)
        {
            WebClient c = new WebClient();
            DataTable dt2 = new DataTable();
            dt2.Columns.Add("Name", typeof(string));
            dt2.Columns.Add("Lat", typeof(string));
            dt2.Columns.Add("Lng", typeof(string));
            dt2.Columns.Add("Vicinity", typeof(string));
            StringBuilder url = new StringBuilder();
            url.Append(NEAR_PLACE_URL + "location=" + location + "&radius="+radius+"&types=" + type + "&sensor=false&language="+lang+"&key=" + key[id]);
            StringBuilder page_token = new StringBuilder();
            do
            {
                string downurl = url.ToString()+page_token.ToString();
                Console.WriteLine(downurl);
                c.Encoding = Encoding.UTF8;
                var data = c.DownloadString(downurl.ToString());
                Console.WriteLine(data);
                JObject o = JObject.Parse(data);
                string status = o["status"].ToString();
                if (status.Equals("OK"))
                {
                    JArray array = JArray.FromObject(o["results"]);
                    foreach (var result in array)
                    {
                        dt2.Rows.Add(result["name"].ToString(), result["geometry"]["location"]["lat"].ToString(), result["geometry"]["location"]["lng"].ToString(), result["vicinity"].ToString());
                    }

                    //dtAll.Merge(dt2.Copy());
                    if (o["next_page_token"] != null)
                    {
                        page_token = new StringBuilder();
                        page_token.Append("&pagetoken=" + o["next_page_token"].ToString().Trim());
                    }
                    else
                    {
                        break;
                    }
                }
                
            }while(page_token.Length>0);

            return dt2;
        }


        public static DataTable getPlaces(DataTable dt1, RouteVO route)
        {
            DataTable dt = new DataTable();
            dt.AcceptChanges();
            List<LatLng> points = route.Points;
            foreach (LatLng point in points)
            {
                DataTable dt2 = dt1.Copy();
                ItemBUS itemBUS = new ItemBUS();
                DataTable dtt = itemBUS.getItemsList(dt2, point.Latitude, point.Longitude, 0.1);
                dt.Merge(dtt.Copy());
                Utility.RemoveDuplicateRows(dt, "ItemID");
            }
            return dt;
        }


        public static string parse(string location, string type)
        {
            WebClient c = new WebClient();
            string pagetoken = null;
            string url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                 + location + "&radius=10000&types=" + type + "&sensor=false&language=vi&key=" + key;
            string downurl = null;
            downurl = url + pagetoken;
            c.Encoding = Encoding.UTF8;
            var data = c.DownloadString(downurl);
            return data;
        }       

    }
}